let result = {};

let sqlConnection = {};
let syncSqlConnection = {};


result.map = {};
result.idMap = {};

/**
 * 初始化
 */
result.init = (connection1, connection2) => {
    sqlConnection = connection1;
    syncSqlConnection = connection2;
}


/**
 * 表名转换为_分割的小写
 */
result.nameToUnderline = (tableName) => {
    return tableName.replace(/([A-Z])/g, "_$1").toLowerCase();
}

/**
 * 获取表的字段
 */
result.getFieldMap = (tableNameInput) => {
    let tableName = result.nameToUnderline(tableNameInput);
    // 获取数据库表中所有字段
    let fieldsAll = [];
    // 如果map中有数据，且不超过2分钟，则直接取map中的数据
    if (result.map[tableName] && new Date().getTime() - result.map[tableName].time < 1200000) {
        fieldsAll = result.map[tableName].fieldsAll;
        for (let i = 0; i < fieldsAll.length; i++) {
            fieldsAll[fieldsAll[i]] = fieldsAll[i];
        }
    } else {
        // 开始时间
        let startTime = new Date().getTime();
        fieldsAll = syncSqlConnection.query(`select COLUMN_NAME from information_schema.COLUMNS where table_name = '${tableName}'`);
        // 结束时间
        let endTime = new Date().getTime();
        console.log("查询字段时间：" + (endTime - startTime), "表名：" + tableName);
        // 放入map中，下次查询不用再次查询
        result.map[tableName] = {fieldsAll: fieldsAll, time: new Date().getTime()};
        for (let i = 0; i < fieldsAll.length; i++) {
            fieldsAll[i] = fieldsAll[i].COLUMN_NAME;
        }
    }
    return fieldsAll;
}

/**
 * 获取查询的字段
 */
result.getField = (tableName,fieldName) => {
    // 将fieldName转换为_分割的小写
    let fieldNameUnderline = result.nameToUnderline(fieldName);
    let fileNamePrefixAdd = "t_"+fieldNameUnderline;
    let fieldsAll = result.getFieldMap(tableName);
    if(fieldsAll.includes(fieldNameUnderline)) {
        return fieldNameUnderline;
    } else if(fieldsAll.includes(fileNamePrefixAdd)) {
        return fileNamePrefixAdd;
    }
    return null;
}

/**
 * 转换为,分割的字符串
 */
result.getFieldsStr = (tableName,fieldNames) => {
    let fields = "*";
    let fieldsAll = result.getFieldMap(tableName);
    if (fieldNames) {
        let fields = "";
        let fieldNames2 = [];
        for (let i = 0; i < fieldNames.length; i++) {
            // 驼峰式转下划线
            fieldNames[i] = result.nameToUnderline(fieldNames[i]);
            fieldNames2.push(fieldNames[i]);
            fieldNames2.push(`t_${fieldNames[i]}`);
        }
        for (let i = 0; i < fieldNames2.length; i++) {
            // 查询在字段中是否存在
            if (fieldsAll.includes(fieldNames2[i])) {
                fields += `${fieldNames2[i]},`;
            }
        }

        fields = fields.substring(0, fields.length - 1);
        if (fields === "") {
            fields = "*";
        }

    }
    return fields;
}


// 发现有字段和fieldsAll不一致，则去掉map对应这个表的数据
result.check = (tableNameInput,fieldsStr,dataList) => {
    if(!dataList||dataList.length===0) {
        return;
    }
    let fieldsAll = [];
    // 获取第一个数据的字段
    let keys = Object.keys(dataList[0]);
    for (let i = 0; i < keys.length; i++) {
        fieldsAll.push(keys[i]);
    }
    setTimeout(() => {
        let tableName = result.nameToUnderline(tableNameInput);
        if (fieldsStr !== "*") {
            let fields2 = fieldsStr.split(",");
            for (let i = 0; i < fields2.length; i++) {
                fields2[i] = fields2[i].replace(/([A-Z])/g, "_$1").toLowerCase();
            }
            for (let i = 0; i < fields2.length; i++) {
                if (!fieldsAll.includes(fields2[i])) {
                    delete result.map[tableName];
                    break;
                }
            }
        }
        // 如果idMap不为空，且不存在idMap中的id字段，且不为空，则删除map中的数据
        if (result.idMap[tableName] && !fieldsAll.includes(result.idMap[tableName].id)) {
            delete result.idMap[tableName];
        }
    });
}


module.exports = result;